package io.itit.ecp.admin.provide.action.controller;

import com.baomidou.mybatisplus.core.metadata.IPage;
import icu.mhb.mybatisplus.plugln.core.JoinLambdaWrapper;
import icu.mhb.mybatisplus.plugln.extend.Joins;
import io.itit.ecp.admin.provide.action.req.CarbonEmissionFactorQueryReq;
import io.itit.ecp.admin.provide.action.req.CarbonEmissionFactorReq;
import io.itit.ecp.admin.provide.action.resp.CarbonEmissionFactorResp;
import io.itit.ecp.admin.provide.helper.CarbonEmissionFactorHelper;
import io.itit.ecp.admin.provide.renderer.CarbonEmissionFactorRenderer;
import io.itit.ecp.admin.server.entity.CarbonEmissionFactorEntity;
import io.itit.ecp.admin.server.entity.EnergyConsumptionTypeEntity;
import io.itit.ecp.admin.server.service.ICarbonEmissionFactorService;
import io.itit.grass.common.exception.GrassException;
import io.itit.grass.common.provide.action.req.BaseBatchIdReq;
import io.itit.grass.common.provide.action.req.BaseIdReq;
import io.itit.grass.common.provide.action.resp.ResultResp;
import io.itit.grass.common.provide.action.validation.*;
import io.itit.grass.common.server.utils.ConvertUtils;
import io.itit.grass.estelle.starter.core.ExcelXSSFUtil;
import io.itit.grass.estelle.starter.parse.ExcelParseManage;
import io.itit.grass.estelle.starter.util.JsonUtil;
import io.itit.grass.web.wall.utils.PageUtils;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.LocalTime;
import java.time.YearMonth;
import java.time.format.DateTimeFormatter;
import java.util.Objects;

/**
 * <p>
 *
 * @Author：Roy
 * @Description：碳排放因子控制类
 * @Date：Create by 2023-11-23 16:28:52
 */
@Api(tags = "碳排放因子")
@RestController
@RequestMapping("/ecp-admin/carbonEmissionFactor")
public class CarbonEmissionFactorController {

    @Resource
    private ICarbonEmissionFactorService carbonEmissionFactorService;

    @ApiOperation("分页查询")
    @PostMapping("queryPage")
    @RequiresPermissions(value = "ecp-admin:carbonEmissionFactor:search")
    public ResultResp<IPage<CarbonEmissionFactorResp>> queryPage(@RequestBody @Validated(IQueryPage.class) CarbonEmissionFactorQueryReq req) {
        return ResultResp.success(buildQW(req).joinPage(PageUtils.getPage(req, CarbonEmissionFactorResp.class), CarbonEmissionFactorResp.class));
    }

    @ApiOperation("详情")
    @PostMapping("detail")
    @RequiresPermissions("ecp-admin:carbonEmissionFactor:search")
    public ResultResp<CarbonEmissionFactorResp> detail(@RequestBody @Validated(IRequired.class) BaseIdReq req) {
        return ResultResp.success(ConvertUtils.copy(carbonEmissionFactorService.getById(req.getId()), CarbonEmissionFactorResp.class));
    }

    /**
     * 组装查询条件
     */
    private static JoinLambdaWrapper<CarbonEmissionFactorEntity> buildQW(CarbonEmissionFactorQueryReq req) {
        LocalDateTime dateStart = null;
        LocalDateTime dateEnd = null;
        if (StringUtils.isNotEmpty(req.getSolidifyDate())) {
            YearMonth yearMonth = YearMonth.parse(req.getSolidifyDate(), DateTimeFormatter.ofPattern("yyyy-MM"));
            dateStart = yearMonth.atDay(1).atTime(LocalTime.MIN);
            dateEnd = LocalDate.of(yearMonth.getYear(), yearMonth.getMonth(), yearMonth.lengthOfMonth()).atTime(LocalTime.MAX);
        }
        return Joins.of(CarbonEmissionFactorEntity.class)
                .selectAll()
                .leftJoin(EnergyConsumptionTypeEntity.class, EnergyConsumptionTypeEntity::getId, CarbonEmissionFactorEntity::getEnergyTypeId)
                .selectAs(EnergyConsumptionTypeEntity::getEnergyName, CarbonEmissionFactorResp::getEnergyTypeName)
                .end()
                .eq(StringUtils.isNotEmpty(req.getEnergyTypeId()), CarbonEmissionFactorEntity::getEnergyTypeId, req.getEnergyTypeId())
                .eq(Objects.nonNull(req.getFactor()), CarbonEmissionFactorEntity::getFactor, req.getFactor())
                .eq(StringUtils.isNotEmpty(req.getRemark()), CarbonEmissionFactorEntity::getRemark, req.getRemark())
                .eq(StringUtils.isNotEmpty(req.getDeptId()), CarbonEmissionFactorEntity::getDeptId, req.getDeptId())
                .in(CollectionUtils.isNotEmpty(req.getIds()), CarbonEmissionFactorEntity::getId, req.getIds())
                .ge(Objects.nonNull(dateStart), CarbonEmissionFactorEntity::getSolidifyDate, dateStart)
                .lt(Objects.nonNull(dateEnd), CarbonEmissionFactorEntity::getSolidifyDate, dateEnd)
                .orderByDesc(CarbonEmissionFactorEntity::getSolidifyDate)
                .orderByDesc(CarbonEmissionFactorEntity::getCreateTm);
    }

    @ApiOperation("新增")
    @PostMapping("add")
    @RequiresPermissions("ecp-admin:carbonEmissionFactor:add")
    public ResultResp<Boolean> add(@RequestBody @Validated({IAdd.class}) CarbonEmissionFactorReq req) {
        Long count = carbonEmissionFactorService.lambdaQuery()
                .eq(CarbonEmissionFactorEntity::getSolidifyDate, req.getSolidifyDate())
                .eq(CarbonEmissionFactorEntity::getEnergyTypeId, req.getEnergyTypeId())
                .count();
        GrassException.throwEx(count > 0, "数据已存在，不能重复新增。");
        CarbonEmissionFactorHelper.i().setCache(req.getEnergyTypeId(), req.getSolidifyDate(), req.getFactor());
        return ResultResp.success(carbonEmissionFactorService.save(ConvertUtils.convertIgnoreId(req, CarbonEmissionFactorEntity.class)));
    }

    @ApiOperation("编辑")
    @PostMapping("update")
    @RequiresPermissions("ecp-admin:carbonEmissionFactor:update")
    public ResultResp<Boolean> update(@RequestBody @Validated({IUpdate.class}) CarbonEmissionFactorReq req) {
        boolean bool = carbonEmissionFactorService.updateCarbonEmissionFactor(ConvertUtils.copy(req, CarbonEmissionFactorEntity.class));
        CarbonEmissionFactorHelper.i().setCache(req.getEnergyTypeId(), req.getSolidifyDate(), req.getFactor());
        return ResultResp.success(bool);
    }

    @ApiOperation("删除(根据Id删)")
    @PostMapping("deleteById")
    @RequiresPermissions("ecp-admin:carbonEmissionFactor:deleteById")
    public ResultResp<Boolean> deleteById(@RequestBody @Validated({IRequired.class}) BaseIdReq req) {
        return ResultResp.success(carbonEmissionFactorService.removeById(req.getId()));
    }

    @ApiOperation("批量删除")
    @PostMapping("batchDelete")
    @RequiresPermissions("ecp-admin:carbonEmissionFactor:batchDelete")
    public ResultResp<Boolean> batchDelete(@RequestBody @Validated({IRequired.class}) BaseBatchIdReq req) {
        return ResultResp.success(carbonEmissionFactorService.removeBatchByIds(req.getIds(), 1000));
    }

    @ApiOperation("导入")
    @PostMapping("upload")
    @RequiresPermissions("ecp-admin:carbonEmissionFactor:upload")
    public ResultResp<Integer> upload(@RequestParam("file") MultipartFile file, Boolean ignoreError) {
        return ResultResp.success(ExcelParseManage.i().process(CarbonEmissionFactorRenderer.ENTITY_NAME, file, ignoreError));
    }

    @ApiOperation("导出")
    @PostMapping("export")
    @RequiresPermissions("ecp-admin:carbonEmissionFactor:export")
    public void export(@RequestBody @Validated(IExport.class) CarbonEmissionFactorQueryReq req, HttpServletResponse response) {
        ExcelXSSFUtil.export("CarbonEmissionFactorExport", JsonUtil.toJson(buildQW(req).joinList(CarbonEmissionFactorResp.class)), response);
    }
}
